package bd

import android.app.Activity
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.provider.MediaStore
import android.util.Log
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.MediaController
import android.widget.VideoView
import androidx.lifecycle.lifecycleScope
import oa.lla.cca.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.*


class CJ : FG() {

    private var videoView:VideoView? = null
    private var mediaController : MediaController? = null
    private var infoBean: FB? = null
    private var countDownTimer:CountDownTimer? = null
    private var isVip = false
    private var currentPosition = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video_details)
        initView()
    }

    private fun initView() {
        infoBean = intent.getSerializableExtra(VIDEO_INFO) as FB?
        currentPosition = intent.getIntExtra(CH.POSITION, 0)
        mediaController = MediaController(this)
        findViewById<ImageView>(R.id.back_left).setOnClickListener { finish() }
        videoView = findViewById(R.id.video_play_vd)
        videoView?.apply {
            setVideoPath(infoBean?.path)
            start()
            setOnPreparedListener {
                countTime()
            }
        }

        findViewById<LinearLayout>(R.id.right_delete).setOnClickListener {
            showAd(true,"video_del")
        }
        findViewById<LinearLayout>(R.id.right_recover).setOnClickListener {
            showAd(false,"video_recover")
        }

        findViewById<LinearLayout>(R.id.details_bottom_bt).setOnClickListener {
            showAd(false,"video_play_all")
        }


    }

    private fun countTime(){
        if (isVip){
            return
        }
        countDownTimer = object :CountDownTimer(3000,1000){
            override fun onTick(millisUntilFinished: Long) {
            }

            override fun onFinish() {
                videoView?.stopPlayback()
            }

        }

        countDownTimer?.start()
//        setMediaController(mediaController)
    }





    override fun onPause() {
        super.onPause()
        videoView?.pause()
    }


    override fun onResume() {
        super.onResume()
        videoView?.start()
    }

    companion object{
        val VIDEO_INFO = "videoInfo"
        val POSITION = "position"
        val PATE_VIDEO = "pageVideo"
        fun intentVideoDetailsActivity(context: Activity, bean: FB, position: Int) {
            val intent = Intent(context, CJ::class.java)
            intent.putExtra(VIDEO_INFO, bean)
            intent.putExtra(POSITION, position)
            context.startActivityForResult(intent,100)
        }
    }




    private fun showAd(isDelete:Boolean,adKey:String){

        if (adKey.equals("video_play_all")){
            isVip = true
            videoView?.apply {
                setMediaController(mediaController)
                setVideoPath(infoBean?.path)
                start()
            }
            return
        }
        if (isDelete){
            File(infoBean?.path!!).delete()
            val intent = Intent()
            intent.putExtra(CH.POSITION,currentPosition)
            intent.putExtra(CH.PAGE_TYPE, PATE_VIDEO)
            setResult(Activity.RESULT_OK,intent)
            finish()
        }else{
            if (infoBean != null) {
                lifecycleScope.launch (Dispatchers.IO){
                    saveVideoToSystemAlbum(infoBean?.path!!,this@CJ)
                }
            }
        }


//        showAdView(null,adKey,object : ScopeFinishListener {
//            override fun showLoading() {
//            }
//
//            override fun hideLoading() {
//            }
//
//            override fun onComplete() {
//
//            }
//
//            override fun toNextAndFinish() {
//            }
//        })
    }






    fun saveVideoToSystemAlbum(videoFile: String?, context: Context): Boolean {
        return try {
            val localContentResolver: ContentResolver = context.getContentResolver()
            val localContentValues: ContentValues =
                getVideoContentValues(File(videoFile), System.currentTimeMillis())!!
            val localUri: Uri = localContentResolver.insert(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                localContentValues
            )!!
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.Q) {
                // 拷贝到指定uri,如果没有这步操作，android11不会在相册显示
                try {
                    val out: OutputStream = context.getContentResolver().openOutputStream(localUri)!!
                    if (videoFile != null) {
                        copyFile(videoFile, out)
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri))
            //将该文件扫描到相册
            //MediaScannerConnection.scanFile(context, new String[] { videoFile }, null, null);
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }


    fun getVideoContentValues(paramFile: File, paramLong: Long): ContentValues? {
        val localContentValues = ContentValues()
        localContentValues.put("title", paramFile.name)
        localContentValues.put("_display_name", paramFile.name)
        localContentValues.put("mime_type", "video/mp4")
        localContentValues.put("datetaken", java.lang.Long.valueOf(paramLong))
        localContentValues.put("date_modified", java.lang.Long.valueOf(paramLong))
        localContentValues.put("date_added", java.lang.Long.valueOf(paramLong))
        localContentValues.put("_data", paramFile.absolutePath)
        localContentValues.put("_size", java.lang.Long.valueOf(paramFile.length()))
        return localContentValues
    }


    fun copyFile(oldPath: String, out: OutputStream): Boolean {
        try {
            var bytesum = 0
            var byteread = 0
            val oldfile = File(oldPath)
            if (oldfile.exists()) {
                // 读入原文件
                val inStream: InputStream = FileInputStream(oldPath)
                val buffer = ByteArray(1444)
                while (inStream.read(buffer).also { byteread = it } != -1) {
                    bytesum += byteread //字节数 文件大小
                    println(bytesum)
                    out.write(buffer, 0, byteread)
                }
                inStream.close()
                out.close()
                return true
            } else {
                Log.i("ddd==", String.format("文件(%s)不存在。", oldPath))
            }
        } catch (e: java.lang.Exception) {
            Log.e("ddd==", "复制单个文件操作出错")
            e.printStackTrace()
        }
        return false
    }


    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.cancel()
    }
}